package reviews

import (
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/factory"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/reviewd"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/base"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/columnd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
)

func createReviewCtrl(d core.CmsDomain) *reviewCtrl {
	return &reviewCtrl{
		BaseContrl: base.BaseContrl{
			Domain: d,
		},
		info:     d.Info(),
		iar:      d.Info().InfoAggregateRoot(),
		car:      d.Column().ColumnAggregateRoot(),
		reviewar: d.Review().ReviewAggregateRoot(),
	}
}

type reviewCtrl struct {
	base.BaseContrl
	info     infod.InfoDomain
	iar      infod.InfoAggregateRoot
	car      columnd.ColumnAggregateRoot
	reviewar reviewd.ReviewAggregateRoot
}

// 分页获取信息列表
func (c reviewCtrl) getReviewList(ctx *gin.Context) {
	targetType := c.ParamInt(ctx, "targetType", -1)
	if targetType == -1 {
		c.ErrBadRequest(ctx, 1, "未指定类型")
		return
	}
	targetID := ctx.Param("targetID")
	if targetID == "" {
		c.ErrBadRequest(ctx, 1, "未指定编号")
		return
	}
	dctx := c.DDDContext(ctx)
	r, err := c.reviewar.QueryAll(dctx, reviewd.ReviewSearch{
		TargetID:   targetID,
		TargetType: targetType,
	})
	if err != nil {
		c.ErrServerError(ctx, 3, "查询失败.", err)
		return
	}
	c.Success(ctx, r)
}

// ReqReviewDesc 请求参数
type ReqReviewDesc struct {
	TargetType int    `json:"target_type" binding:"required,eq=1|eq=2"` // 类型 1.信息，2评论，
	TargetID   string `json:"target_id" binding:"required,max=36"`      // id
	Result     bool   `json:"result"`                                   // 审核结果 true 审核通过，false 审核不通过
	Reason     string `json:"reason" binding:"max=100"`                 // 审核理由
}

// CustomValid 自定义验证函数
func (r ReqReviewDesc) CustomValid() error {
	if !r.Result && r.Reason == "" {
		return errors.Errorf("审核不通过必须设置reason字段")
	}
	return nil
}

func (c reviewCtrl) add(ctx *gin.Context) {
	var req ReqReviewDesc

	if err := ctx.BindJSON(&req); err != nil {
		c.ErrBadRequestByBind(ctx, 1, err)
		return
	}
	dctx := c.DDDContext(ctx)
	if req.Result {
		if err := factory.DefaultFactory.ReviewOK(dctx, req.TargetType, req.TargetID, req.Reason, dctx.UID()); err != nil {
			c.ErrServerError(ctx, 2, "审核失败", err)
			return
		}
	} else {
		if err := factory.DefaultFactory.ReviewNo(dctx, req.TargetType, req.TargetID, req.Reason, dctx.UID()); err != nil {
			c.ErrServerError(ctx, 3, "审核失败", err)
			return
		}
	}
	c.Success(ctx, nil)
}
